﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class GPSGroupsByGPSStock : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                sdsGPSType.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;
                sdsGPSModels.ConnectionString = GPSTrackingDBV2.Data.DataRepository.ConnectionStrings["netTiersConnectionString"].ConnectionString;

                if (!Page.IsPostBack)
                {
                    GridSortExpression expression = new GridSortExpression();
                    expression.FieldName = "GPSGroupIdSource.Name";
                    expression.SetSortOrder("Ascending");
                    this.GPSGroupsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);

                    expression = new GridSortExpression();
                    expression.FieldName = "GpsImeiSource.Name";
                    expression.SetSortOrder("Ascending");
                    this.GPSSelectedGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
                }
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede iniciar los datos de la sección");
            }
        }       

        private GPSTrackingDBV2.Entities.GpsGroups Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.GpsGroups GpsGroupsEntity = new GPSTrackingDBV2.Entities.GpsGroups();
            try
            {
                GpsGroupsEntity.GpsGroupId = Convert.ToInt32(Entity[GPSTrackingDBV2.Entities.GpsGroupsColumn.GpsGroupId.ToString()]);
                GpsGroupsEntity.Name = Entity["GPSGroupIdSource.Name"].ToString();
            }
            catch (Exception ex) {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede iniciar los datos de la sección");
            }
            return GpsGroupsEntity;
        }

        protected void GPSGroupsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                SessionManager objSessionManager = new SessionManager();
                objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

                getGPSGroupsByCompanyID(objSessionManager.CompanyIDSelectedComboBox);
                ResizeGrid();
            }
            catch (Exception ex) {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede cargar los datos de los grupos");
            }
        }
        
        protected void getGPSGroupsByCompanyID(int companyID)
        {
            try
            {
                GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.CompaniesByGpsGroups> CompaniesByGpsGroupsEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesByGpsGroupsProvider.GetByCompanyId(companyID);
                GPSTrackingDBV2.Data.DataRepository.CompaniesByGpsGroupsProvider.DeepLoad(CompaniesByGpsGroupsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.GpsGroups));
                GPSGroupsGrid.DataSource = CompaniesByGpsGroupsEntity;
            }
            catch (Exception ex) {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede crear los datos de los grupos");
            }
        }

        protected void GPSGroupsGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int gpsGroupId = getGPSGroupIDSelected();
            HttpContext.Current.Session["GPSGroupID"] = gpsGroupId; 
            GetGPSStockByGPSGroupID(gpsGroupId);
            GPSSelectedGrid.DataBind();
            ResizeGrid();
        }

        protected int getGPSGroupIDSelected(){

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in GPSGroupsGrid.SelectedItems)
                {
                    return int.Parse(selectedItem["GPSGroupId"].Text);
                }
            }
            catch {}
            return -1;
        }

        protected void GPSSelectedGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetGPSStockByGPSGroupID(getGPSGroupIDSelected());
            ResizeGrid();
        }

        protected void uscGPSSearchCombo_OnAcceptEvent(List<GridDataItem> rows)
        {

            int GPSGroupID = getGPSGroupIDSelected();

            if (GPSGroupID == -1 && rows.Count > 0)
            {
                showErrorMessage("Debe seleccionar un master para asociar las pantallas.");
            }
            else
            {

                foreach (GridDataItem row in rows)
                {
                    GPSTrackingDBV2.Entities.GpsStockByGpsGroups GpsStockByGpsGroupsEntity = new GPSTrackingDBV2.Entities.GpsStockByGpsGroups();
                    
                    GpsStockByGpsGroupsEntity.Dispose();
                    GpsStockByGpsGroupsEntity.GpsGroupId = GPSGroupID;
                    GpsStockByGpsGroupsEntity.GpsImei = row.Cells[3].Text;

                    GPSTrackingDBV2.Data.DataRepository.GpsStockByGpsGroupsProvider.Insert(GpsStockByGpsGroupsEntity);
                }
                GetGPSStockByGPSGroupID(GPSGroupID);
                GPSSelectedGrid.DataBind();
            }
            ResizeGrid();
        }

        protected void uscGPSSearchCombo_OnCancelEvent()
        {
            ResizeGrid();
        }

        protected void GetGPSStockByGPSGroupID(int gpsGroupID)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.GpsStockByGpsGroups> GpsStockByGpsGroupsEntity = GPSTrackingDBV2.Data.DataRepository.GpsStockByGpsGroupsProvider.GetByGpsGroupId(gpsGroupID);
            GPSTrackingDBV2.Data.DataRepository.GpsStockByGpsGroupsProvider.DeepLoad(GpsStockByGpsGroupsEntity, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.GpsStock));
            GPSSelectedGrid.DataSource = GpsStockByGpsGroupsEntity;            
        }

        protected void GPSSelectedGrid_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Data.DataRepository.GpsStockByGpsGroupsProvider.Delete(tm, Entity["GpsImeiSource.GpsImei"].ToString(), getGPSGroupIDSelected());
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);
                showErrorMessage("No se puede borrar el dispositivo");
            }
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            GPSGroupsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in GPSGroupsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            clearSelectedGrid();
            GPSGroupsGrid.MasterTableView.Rebind();
            ResizeGrid();
        }

        protected void lbClearFilters2_Click(object sender, EventArgs e)
        {
            GPSSelectedGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in GPSSelectedGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }


            GPSSelectedGrid.MasterTableView.Rebind();
        }

        private void ResizeGrid()
        { 
            decimal Height =Convert.ToDecimal(HiddenFieldHeight.Value) / 2;
            GPSGroupsGrid.Height = Unit.Parse(Convert.ToString(Height));
            GPSSelectedGrid.Height = Unit.Parse(Convert.ToString(Height));        
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Grupos de dispositivos ...');", true);
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        protected void lbShowError2_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        private void clearSelectedGrid()
        {
            GPSSelectedGrid.DataSource = new string[] { };
            GPSSelectedGrid.DataBind();
            ResizeGrid();
        }

        protected void GPSGroupsGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearSelectedGrid();
            }
        }

    }
}